package code.BinaryTree;

import struct.Tree;
import struct.TreeNode;

import java.util.ArrayList;
import java.util.Iterator;

public class PrintTree {
	public static void main(String[] args) {
		TreeNode tree = Tree.constructTree("[1,2,3,4,5,5,6,null,7,10,null,8,9]");
		PrintTree printTree = new PrintTree();
		printTree.printTreeHorizontal(tree);
		printTree.printTreeVertical(tree);
	}

	public void printTreeHorizontal(TreeNode head) {
		printTreeHorizontalHelper(head, 0, "H", 17);//17是保留的最大宽度
	}

	public void printTreeHorizontalHelper(TreeNode head, int h, String to, int len) {
		if (head == null) {
			return;
		}
		printTreeHorizontalHelper(head.right, h + 1, "v", len);
		String print = to + head.val + to;
		int lLen = (len - print.length()) / 2;
		int rLen = len - lLen - print.length();
		String s = getSpace(lLen) + print + getSpace(rLen);
		System.out.println(getSpace(h * len) + s);
		printTreeHorizontalHelper(head.left, h + 1, "^", len);
	}

	public void printTreeVertical(TreeNode head) {
		int h = new TreeDepth().maxDepth(head);
		ArrayList<String[]> arrayList = new ArrayList<>();
		printTreeVerticalHelper(head, 0, h, 8, arrayList);
		int length = arrayList.get(0).length;
		for (int i = 0; i < length; i++) {
			for (int i1 = 0; i1 < arrayList.size(); i1++) {
				System.out.print(arrayList.get(i1)[i]);
			}
			System.out.println("\n");
		}
	}

	public void printTreeVerticalHelper(TreeNode head, int h, int maxH, int len, ArrayList<String[]> arrayList) {
		if (head == null) {
			return;
		}
		printTreeVerticalHelper(head.left, h + 1, maxH, len, arrayList);
		setVertiaclSpace(arrayList, head.val, maxH, h, len);
		printTreeVerticalHelper(head.right, h + 1, maxH, len, arrayList);
	}

	public void setVertiaclSpace(ArrayList<String[]> arrayList, int val, int maxH, int h, int len) {
		String[] strings = new String[maxH];
		for (int i = 0; i < strings.length; i++) {
			strings[i] = getSpace(len);
		}
		String print = val + "";
		int lLen = (len - print.length()) / 2;
		int rLen = len - lLen - print.length();
		String s = getSpace(lLen) + print + getSpace(rLen);
		strings[h] = s;
		arrayList.add(strings);
	}

	public String getSpace(int num) {
		return " ".repeat(Math.max(0, num));
	}

}
